<?php

namespace Client\Model;

use ArrayObject;
use Zend\Db\Adapter\Driver\ConnectionInterface;
use Zend\Db\TableGateway\TableGateway;

class ClientTable
{
    protected $tableGateway;
    protected $adapter;

    public function __construct(TableGateway $tableGateway)
    {
        $this->tableGateway = $tableGateway;
        $this->adapter = $tableGateway->getAdapter();
    }

    public function fetchAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet;
    }

    /**
     * 查询客户
     * @param null $column
     * @param null $parame
     * @param int $offset
     * @param int $limit
     * @return array|ConnectionInterface|null
     */
    public function findClient($column = null, $parame = null, $offset, $limit)
    {
        $connection = $this->adapter->getDriver()->getConnection();
        try {
            $connection->beginTransaction();
            $select = $this->tableGateway->getSql()->select()->limit($limit)->offset($offset);
            if ($column) $select->where->like($column, '%' . $parame . '%');
            $resultSet = $this->tableGateway->selectWith($select);
            if (is_null($resultSet)) return $resultSet;
            return $resultSet->toArray();
            $connection->commit();
        } catch (\Exception $exception) {
            return $connection->rollback();
        }
    }

    /**
     * 获取客户
     * @param $client_id
     * @return array|ArrayObject
     * @throws \Exception
     */
    public function getClient($client_id)
    {
        $rowset = $this->tableGateway->select(array('client_id' => $client_id));
        $row = $rowset->current();
        if (!$row) throw new \Exception("Could not find doc by $client_id");
        return $row;
    }

    /**
     * 编辑客户
     * @param Client $client
     * @return int
     * @throws \Exception
     */
    public function setClient(Client $client)
    {
        $data = array(
            'client_name' => $client->client_name,
            'client_city' => $client->client_city
        );
        $client_id = $client->client_id;
        $result = null;
        if (is_null($client_id)) $result = $this->tableGateway->insert($data);
        elseif ($this->getClient($client_id)) $result = $this->tableGateway->update($data, array('client_id' => $client_id));
        else throw new \Exception('Staff id does not exist');
        return $result;
    }

    /**
     * 删除客户
     * @param $client_id
     */
    public function deleteClient($client_id)
    {
        $this->tableGateway->delete(array('client_id' => $client_id));
    }

    /**
     * 根据职工获取客户
     * @param $staff_id
     * @return array
     */
    public function getClientByStaffId($staff_id)
    {
        $sql = "SELECT * FROM pc_client WHERE client_id IN (SELECT client_id FROM pc_responsible WHERE staff_id = '" . $staff_id . "');";
        $resultSet = $this->tableGateway->getAdapter()->query($sql, array());
        return $resultSet->toArray();
    }
}